package com.barunsw.bwf.ems.tool.nas_agent;

import java.util.Properties;

import javax.annotation.PostConstruct;

import org.omg.CORBA.ORB;
import org.omg.PortableServer.POA;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.barunsw.bwf.ems.dto.NeIorVo;
import com.barunsw.bwf.ems.neoarena.ne.NeIorDao;
import com.barunsw.bwf.ems.util.IPUtil;

@Component
public class NasAgent extends Thread {
    private static final Logger LOGGER = LoggerFactory.getLogger(NasAgent.class);
    
	@Autowired
	NeIorDao neIorDao;

    @PostConstruct
    public void startAgent() {
    	start();
    }
	
    private void initCorba() throws Exception {
    	Properties props = System.getProperties();
    	
		props.put("org.omg.CORBA.ORBClass", "org.jacorb.orb.ORB");
		props.put("org.omg.CORBA.ORBSingletonClass", "org.jacorb.orb.ORBSingleton");
		
    	ORB orb = ORB.init((String[])null, props);
		
		POA rootPoa = org.omg.PortableServer.POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
		rootPoa.the_POAManager().activate();
		
		org.omg.CORBA.Object nasObj = rootPoa.servant_to_reference( new NasImpl() );
		
		String iorText = orb.object_to_string(nasObj);
		
		NeIorVo neIorVo = new NeIorVo();
		
		neIorVo.setIpAddress(IPUtil.getLocalIP());
		neIorVo.setIorText(iorText);
		
		long nodeId = IPUtil.convertLong(IPUtil.getLocalIP());
		
		LOGGER.debug(String.format("localIp:%s, nodeId:%s", IPUtil.getLocalIP(), nodeId));
		
		NeIorVo selectedNeIorVo = neIorDao.select(nodeId);
		
		LOGGER.debug("selectedNeIorVo:" + selectedNeIorVo);
		
		if ( selectedNeIorVo != null ) {
			LOGGER.error("DELETE!!!!");
			neIorDao.delete(nodeId);
		}
		
		neIorDao.insert(neIorVo);
		
		LOGGER.info(iorText);
		
		orb.run();
    }
    
    @Override
    public void run() {
		try {
			initCorba();
		}
		catch ( Exception ex ) {
			LOGGER.error(ex.getMessage(), ex);
		}
    }
}
